import type { RouteRecordRaw } from "vue-router";
import { constantRoutes, asyncRouterMap } from "@/router";
import { store, useUserStore } from "@/store";
import router from "@/router";
import { type UserInfo } from "@/api/auth";

export const usePermissionStore = defineStore("permission", () => {
  // 储所有路由，包括静态路由和动态路由
  const routes = ref<RouteRecordRaw[]>([]);
  // 混合模式左侧菜单路由
  const mixedLayoutLeftRoutes = ref<RouteRecordRaw[]>([]);
  // 路由是否加载完成
  const isRoutesLoaded = ref(false);

  /**
   * 获取后台动态路由数据，解析并注册到全局路由
   *
   * @returns Promise<RouteRecordRaw[]> 解析后的动态路由列表
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve) => {
      // 在此处过滤路由
      // 用户状态管理器
      const userStore = useUserStore();
      // 获取用户信息
      const userInfo: UserInfo = userStore.userInfo;
      // 获取用户权限
      const adminPermission: string[] = userInfo.adminPermission;
      // 获取用户身份
      const roles: string[] = userInfo.roles;
      // 通过接口获取动态路由
      const dynamicRoutes =
        roles[0] === "root" ? asyncRouterMap : filterAsyncRoutes(asyncRouterMap, adminPermission);
      routes.value = [...constantRoutes, ...dynamicRoutes];
      isRoutesLoaded.value = true;
      resolve(dynamicRoutes);
    });
  }
  /**
   * 递归过滤异步路由表（适配数组参数版）
   * @param routes 需要过滤的路由数组
   * @param permissions 权限名称数组（示例：["dashboard", "dataBoard"]）
   * @returns 过滤后的路由数组
   */
  const filterAsyncRoutes = (routes: RouteRecordRaw[], permissions: string[]): RouteRecordRaw[] => {
    const permissionSet = new Set(permissions);

    return routes.filter((route) => {
      // 先处理子路由（深度优先）
      if (route.children) {
        route.children = filterAsyncRoutes(route.children, permissions);
      }

      // 满足以下条件之一则保留路由：
      // 1. 路由有名称且在权限集合中
      // 2. 存在有效子路由（用于展示父级菜单）
      const hasPermission = route.name && permissionSet.has(route.name.toString());
      const hasValidChildren = route.children && route.children.length > 0;

      return hasPermission || hasValidChildren;
    });
  };

  /**
   * 根据父菜单路径设置混合模式左侧菜单
   *
   * @param parentPath 父菜单的路径，用于查找对应的菜单项
   */
  const setMixedLayoutLeftRoutes = (parentPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === parentPath);
    if (matchedItem && matchedItem.children) {
      mixedLayoutLeftRoutes.value = matchedItem.children;
    }
  };

  /**
   * 重置路由
   */
  const resetRouter = () => {
    // 清空本地存储的路由和菜单数据
    routes.value = [];
    mixedLayoutLeftRoutes.value = [];
    // 从 Vue Router 中移除所有动态注册的路由
    router.getRoutes().forEach((route) => {
      if (route.name) {
        router.removeRoute(route.name);
      }
    });
    isRoutesLoaded.value = false;
  };

  return {
    routes,
    mixedLayoutLeftRoutes,
    isRoutesLoaded,
    generateRoutes,
    setMixedLayoutLeftRoutes,
    resetRouter,
  };
});

/**
 * 在组件外使用 Pinia store 实例 @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
